package com.xiaoyu.awakening.common.core.kit;

import lombok.Getter;
import lombok.extern.log4j.Log4j2;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * HostNameKit
 *
 * @author wangxiaoyu
 * @since v1.0
 */
@Log4j2
public final class HostNameKit {

    @Getter
    private static String ip;
    @Getter
    private static String hostName;

    static {
        try {
            resolveHost();
        } catch (Exception e) {
            log.error("resolveHost error",e);
        }
    }

    private static void resolveHost() throws Exception {
        InetAddress ipAddress = InetAddress.getLocalHost();
        hostName = ipAddress.getHostName();
        ip = ipAddress.getHostAddress();
        if (ipAddress.isLoopbackAddress()) {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface in = interfaces.nextElement();
                Enumeration<InetAddress> addresses = in.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        ip = address.getHostAddress();
                    }
                }
            }
        }
    }

    public static String getConfigString() {
        return "{\n"
                + "\t\"machine\": \"" + hostName + "\",\n"
                + "\t\"ip\": \"" + ip + "\"\n"
                + "}";
    }

    private HostNameKit() {
    }
}
